package com.ifast.oupei.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.w3c.dom.Document;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ifast.common.base.BaseController;
import com.ifast.common.domain.DictDO;
import com.ifast.common.service.DictService;
import com.ifast.oupei.domain.AnalyseDO;
import com.ifast.oupei.domain.ItemsDO;
import com.ifast.oupei.domain.LeagueDO;
import com.ifast.oupei.domain.MatchDO;
import com.ifast.oupei.domain.OddsDO;
import com.ifast.oupei.service.AnalyseService;
import com.ifast.oupei.service.ItemsService;
import com.ifast.oupei.service.LeagueService;
import com.ifast.oupei.service.MatchService;
import com.ifast.oupei.service.OddsService;
import com.ifast.oupei.util.PDFParserUtil;
import com.ifast.oupei.vo.LeagueVO;
import com.ifast.oupei.vo.MatchVO;
import com.ifast.common.utils.Result;

/**
 * 
 * <pre>
 * 比赛信息表
 * </pre>
 * 
 * <small> 2018-04-23 12:22:35 | Aron</small>
 */
@Controller
@RequestMapping("/oupei/match")
public class MatchController extends BaseController {
	@Autowired
	private MatchService matchService;
	@Autowired
	private LeagueService leagueService;
	@Autowired
	DictService dictService;
	@Autowired
	AnalyseService analyseService;
	@Autowired
	ItemsService itemsService;
	@Autowired
	OddsService oddsService;

	@GetMapping()
	@RequiresPermissions("oupei:match:match")
	String Match() {
		return "oupei/match/match";
	}

	@GetMapping("/notAnalyseMatch")
	@RequiresPermissions("oupei:match:match")
	String NotAnalyseMatch() {
		return "oupei/match/notAnalyse";
	}

	@GetMapping("/errorAnalyseMatch")
	@RequiresPermissions("oupei:match:match")
	String ErrorAnalyseMatch() {
		return "oupei/match/errorAnalyse";
	}

	@GetMapping("/isQuestionMatch")
	@RequiresPermissions("oupei:match:match")
	String IsQuestionMatch() {
		return "oupei/match/isQuestion";
	}

	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("oupei:match:match")
	public Result<Page<MatchDO>> list(MatchDO matchDTO) {
		Page<MatchDO> page = matchService.ListAllMatchInfo(getPage(MatchDO.class));
		return Result.ok(page);
	}

	@ResponseBody
	@GetMapping("/listNotAnalyseMatch")
	@RequiresPermissions("oupei:match:match")
	public Result<Page<MatchDO>> listNotAnalyseMatch(MatchDO matchDTO) {
		Page<MatchDO> page = matchService.selectisNotAnalyseMatchList(getPage(MatchDO.class));
		return Result.ok(page);
	}

	@ResponseBody
	@GetMapping("/listErrorAnalyseMatch")
	@RequiresPermissions("oupei:match:match")
	public Result<Page<MatchDO>> listErrorAnalyseMatch(MatchDO matchDTO) {
		Page<MatchDO> page = matchService.selectErrorAnalyseMatchList(getPage(MatchDO.class));
		return Result.ok(page);
	}

	@ResponseBody
	@GetMapping("/listIsQuestionMatch")
	@RequiresPermissions("oupei:match:match")
	public Result<Page<MatchDO>> listIsQuestionMatch(MatchDO matchDTO) {
		Page<MatchDO> page = matchService.selectisQuestionMatchList(getPage(MatchDO.class));
		return Result.ok(page);
	}

	@GetMapping("/add")
	@RequiresPermissions("oupei:match:add")
	String add(Model model) {
		List<String> leagueList = leagueService.listAllLeagueName();
		model.addAttribute("leagueList", leagueList);
		return "oupei/match/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("oupei:match:edit")
	String edit(@PathVariable("id") Integer id, Model model) {
		MatchDO match = matchService.selectByMatchId(id);
		model.addAttribute("match", match);
		return "oupei/match/edit";
	}

	/**
	 * 添加比赛分析信息
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping("/editAnalyse/{id}")
	@RequiresPermissions("oupei:match:edit")
	String editAnalyse(@PathVariable("id") Integer id, Model model) {
		MatchDO match = matchService.selectByMatchId(id);

		List<DictDO> powerList = dictService.getListByType("team_power");// 广义实力
		model.addAttribute("powerList", powerList);// 广义实力

		List<DictDO> resultList = dictService.getListByType("prediction_result");// 预测结果
		model.addAttribute("resultList", resultList);// 预测结果

		List<ItemsDO> itemsList = itemsService.listAllItems();

		model.addAttribute("itemsList", itemsList);

		model.addAttribute("match", match);
		return "oupei/match/editAnalyse";
	}

	/**
	 * 保存分析比赛到数据库
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@ResponseBody
	@PostMapping("/saveAnalyse")
	public Result<String> saveAnalyse(MatchDO match, AnalyseDO analyseDO) {
		analyseService.insert(analyseDO);
		return Result.ok();
	}

	/**
	 * 二级联动，根据联赛id获取赛季
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/getSeason", method = RequestMethod.POST)
	@ResponseBody
	String getSeason(@RequestParam String id) {
		List<String> leagueList = leagueService.listAllSeaon(id);
		return JSON.toJSONString(leagueList);
	}

	/**
	 * 三级联动，根据联赛名称和赛季获取轮次
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/getTurn", method = RequestMethod.POST)
	@ResponseBody
	String getTurn(@RequestParam String leagueName, @RequestParam String season) {
		List<LeagueVO> leagueList = leagueService.listAllTurn(leagueName, season);
		return JSON.toJSONString(leagueList);
	}

	/**
	 * 保存
	 * 
	 * @throws IOException
	 */
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("oupei:match:add")
	public Result<String> save(String leagueName, String season, String cupMatchDetail) throws IOException {
		return Result.ok(matchService.save(leagueName, season, cupMatchDetail));
	}

	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("oupei:match:edit")
	public Result<String> update(MatchDO match) {
		matchService.updateById(match);
		return Result.ok();
	}

	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@ResponseBody
	@RequiresPermissions("oupei:match:remove")
	public Result<String> remove(Integer id) {
		matchService.deleteById(id);
		oddsService.delete(new EntityWrapper<OddsDO>().where("match_id = {0}", id));// 删除赔率信息
		analyseService.delete(new EntityWrapper<AnalyseDO>().where("match_id = {0}", id));// 删除分析信息
		return Result.ok();
	}

	/**
	 * 删除
	 */
	@PostMapping("/batchRemove")
	@ResponseBody
	@RequiresPermissions("oupei:match:batchRemove")
	public Result<String> remove(@RequestParam("ids[]") Integer[] ids) {
		matchService.deleteBatchIds(Arrays.asList(ids));
		for (Integer i = 0; i < ids.length; i++) {
			oddsService.delete(new EntityWrapper<OddsDO>().where("match_id = {0}", ids[i]));// 删除赔率信息
			analyseService.delete(new EntityWrapper<AnalyseDO>().where("match_id = {0}", ids[i]));// 删除分析信息
		}
		return Result.ok();
	}

	/**
	 * 联赛数据管理
	 * 
	 * @return
	 */
	@GetMapping(value = { "/league/{name}", "/league/{name}/{season}", "/league/{name}/{season}/{turn}" })
	@RequiresPermissions("oupei:match:match")
	String league(@PathVariable(value = "name") String name,
			@PathVariable(value = "season", required = false) String season,
			@PathVariable(value = "turn", required = false) String turn, Model model) {
		// name=name.replace("'", "");
		List<LeagueDO> leagueList = leagueService.listLeagueByName(name);
		Integer id = leagueList.get(0).getId();
		if (season == null) {
			season = leagueList.get(0).getSeason();// leagueService.getSeason(name).getSeason();
		}
		if (turn == null) {
			// leagueService.getSeason(name).getId();
			turn = matchService.getTurn(id);
		}
		model.addAttribute("name", name);// 把联赛名称放入model中
		model.addAttribute("season", season);// 把联赛赛季放入model中
		model.addAttribute("turn", turn);// 把联赛轮次放入model中
		model.addAttribute("leagueList", leagueList);// 把联赛信息放入model中
		model.addAttribute("league", leagueList.get(0));// 默认的赛季信息放入到视图中
		// 添加轮次
		List<String> turnList = new ArrayList<String>();
		for (LeagueDO leagueDO : leagueList) {
			Integer ids = leagueDO.getId();
			String[] a = matchService.getTurnList(ids);
			for (String a1 : a) {
				turnList.add(a1);
			}
		}
		model.addAttribute("turnList", turnList);// 把轮次信息放入model中
		// 把比赛相关信息放入到视图中
		model.addAttribute("matchList", matchService.getMatchByIdAndTurn(id, turn));
		return "oupei/match/league";
	}
	/**
	 * 导出pdf文件
	 * @param turn:轮次
	 * @param id：联赛id
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@GetMapping(value={"/download/{turn}/{id}","/download/{turn}"})
	@RequiresPermissions("oupei:match:match")
	String download(@PathVariable(value = "turn") String turn, @PathVariable(value = "id",required = false) Integer id,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		List<MatchVO> matchList = new ArrayList<MatchVO>();
		boolean all =true;//是否整轮导出的标示
		if(id==null){
			all=false;//不是整轮导出
			String ids[] = turn.split("-");
			for (int i =1;i<ids.length;i++) {
				matchList.add(matchService.getMatchInfo(Integer.parseInt(ids[i])));
			}
		}else{
			matchList=matchService.getMatchByIdAndTurn(id,turn);
		}
		List<Document> docs = matchService.getDocuments(matchList,all);// 获取document
		File file = PDFParserUtil.getPdfOutputStream(docs);// 获取pdf文件

		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("UTF-8");
		java.io.BufferedInputStream bis = null;
		java.io.BufferedOutputStream bos = null;

		try {
			long fileLength = file.length();
			response.setContentType("application/msword");
			response.setHeader("Content-disposition",
					"attachment; filename=" + URLEncoder.encode("导出数据" + ".pdf", "utf-8"));
			response.setHeader("Content-Length", String.valueOf(fileLength));
			bis = new BufferedInputStream(new FileInputStream(file));
			bos = new BufferedOutputStream(response.getOutputStream());
			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bis != null)
				bis.close();
			if (bos != null)
				bos.close();
		}

		return null;

	}

	/**
	 * 分析比赛
	 * 
	 * @param ticketsId
	 *            比赛id
	 * @param model
	 * @return
	 */
	@GetMapping(value = { "/analysis/{ticketsId}" })
	@RequiresPermissions("oupei:match:match")
	String analysis(@PathVariable("ticketsId") Integer ticketsId, Model model) {
		MatchVO match = matchService.getMatchInfo(ticketsId);
		int historyLimit = 5;
		int homeLimit = 5;
		int guestLimit = 5;
		String date =new SimpleDateFormat("YYYY-MM-DD").format(match.getMatchDate());
		// 历史战绩
		List<MatchVO> historyMatchList = matchService.getHistoryMatchList(match.getHometeamId(), match.getGuestteamId(),
				date,historyLimit,21,match.getId());
		// 主队近期战绩
		List<MatchVO> homeMatchList = matchService.getLateMatchList(match.getHometeamId(),date, homeLimit,21,match.getId());
		// 客队近期战绩
		List<MatchVO> guestMatchList = matchService.getLateMatchList(match.getGuestteamId(),date, guestLimit,21,match.getId());
		model.addAttribute("match", match);// 比赛信息
		model.addAttribute("historyMatchList", historyMatchList);// 历史战绩

		model.addAttribute("homeMatchList", homeMatchList);// 主队近期战绩
		model.addAttribute("guestMatchList", guestMatchList);// 客队近期战绩

		if (match.getScore() != null) {
			String[] scores = match.getScore().split("-");
			model.addAttribute("homeScore", scores[0]);// 主队进球
			model.addAttribute("guestScore", scores[1]);// 客队进球
		}
		return "oupei/match/analyse";
	}

	/**
	 * 获取历史数据信息
	 * 
	 * @param hometeamId
	 * @param guestteamId
	 * @param limit
	 * @param model
	 * @return
	 */
	@ResponseBody
	@GetMapping("/geHistoryMatch/{hometeamId}/{guestteamId}/{date}/{limit}")
	@RequiresPermissions("oupei:match:match")
	String geHistoryMatch(@PathVariable("hometeamId") Integer hometeamId,
			@PathVariable("guestteamId") Integer guestteamId, @PathVariable("date") String date,
			@PathVariable("limit") Integer limit,@PathVariable("id") Integer id, Model model) {
		StringBuffer matchInfo = new StringBuffer();
		matchInfo.append("<table class=\"table table-hover table-bordered\">");
		matchInfo.append("<thead><tr class=\"bg-success\">").append("<th class=\"col-1 text-center\">时间</th>")
				.append("<th class=\"col-1 text-center\">联赛</th>").append("<th class=\"col-1 text-center\">轮次</th>")
				.append("<th class=\"col-1 text-center\">主队</th>").append("<th class=\"col-1 text-center\">比分</th>")
				.append("<th class=\"col-1 text-center\">客队</th>")
				.append("<th class=\"col-3 text-center\">分析</th></tr></thead><tbody>");
		int historyLimit = 5;
		// 历史战绩
		List<MatchVO> historyMatchList = matchService.getHistoryMatchList(hometeamId, guestteamId,date, historyLimit,21,id);

		for (MatchVO matchVO : historyMatchList) {
			matchInfo.append("<tr>");
			matchInfo.append("<td class=\"col-1 text-center\">")
					.append(new SimpleDateFormat("yyyy-MM-dd  HH:mm").format(matchVO.getMatchDate())).append("</td>");
			matchInfo.append("<td class=\"col-1 text-center\">").append(matchVO.getLeagueName()).append("</td>");
			matchInfo.append("<td class=\"col-1 text-center\">").append(matchVO.getTurn()).append("</td>");
			matchInfo.append("<td class=\"col-1 text-center\">").append(matchVO.getHomeTeam()).append("</td>");
			matchInfo.append("<td class=\"col-1 text-center\">").append(matchVO.getScore()).append("</td>");
			matchInfo.append("<td class=\"col-1 text-center\">").append(matchVO.getGuestTeam()).append("</td>");
			matchInfo.append("</tr>");
		}
		matchInfo.append("</tbody></table>");
		return matchInfo.toString();
	}

}
